package com.tiennt.android.callnotes.models;

import com.tiennt.android.callnotes.PopupNotesActivity;
import com.tiennt.android.callnotes.db.DbAdapter;
import com.tiennt.android.callnotes.utils.ProjectUtils;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;

public class OutgoingReceiver extends BroadcastReceiver {
	public OutgoingReceiver() {
	}

	@Override
	public void onReceive(final Context context, Intent intent) {
		final String number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);

		new Handler().postDelayed(new Runnable() {
			public void run() {
				Bundle data = new Bundle();
				String contactId = "";
				Uri contackLookup = Uri.withAppendedPath(
						ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
						Uri.encode(number));

				Cursor cursor = context.getContentResolver().query(
						contackLookup,
						new String[] { ContactsContract.PhoneLookup._ID, },
						null, null, null);

				if (cursor != null) {
					if (cursor.moveToFirst()) {
						contactId = cursor.getString(cursor
								.getColumnIndex(ContactsContract.PhoneLookup._ID));
						data.putString(ProjectUtils.BUNDLEKEY_CONTACTID,
								contactId);
						data.putInt(ProjectUtils.BUNDLEKEY_CALLTYPE,
								ProjectUtils.CALLTYPE_OUTGOING);
					}
					cursor.close();
				}

				DbAdapter adapter = new DbAdapter(context);
				adapter.open();
				if (adapter.getCount(contactId, ProjectUtils.CALLTYPE_OUTGOING) != 0) {
					Intent intentPhoneCall = new Intent(context,
							PopupNotesActivity.class);
					intentPhoneCall.putExtras(data);
					intentPhoneCall.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					intentPhoneCall.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
					intentPhoneCall.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

					context.startActivity(intentPhoneCall);
				}
				adapter.close();
			}
		}, 1000);

	}

}
